
package com.joysuch.wwyt.core.support;

import java.util.ArrayList;
import java.util.List;

import com.joysuch.wwyt.core.sqlparser.SqlParserInterceptor;
import com.joysuch.wwyt.core.sqlparser.impl.DataPermissionSqlParserInterceptor;
import com.joysuch.wwyt.core.sqlparser.impl.TenantAndOrgCodeSqlParserInterceptor;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TenantAndDataruleInterceptor implements StatementInspector {

    private static final Logger logger = LoggerFactory.getLogger("SqlInterceptor");

    List<SqlParserInterceptor> interceptors = new ArrayList<>(3);

    public TenantAndDataruleInterceptor() {
        interceptors.add(new TenantAndOrgCodeSqlParserInterceptor());
        interceptors.add(new DataPermissionSqlParserInterceptor());
    }

    boolean support() {
        if (interceptors.isEmpty()) {
            return false;
        }
        for (SqlParserInterceptor s : interceptors) {
            if (s.support()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String inspect(String sql) {
        if (sql.startsWith("{")) {
            logger.warn("含有{的无效sql: {}", sql);
            return sql;
        }
        if (support()) {
            try {
                long start = System.currentTimeMillis();
                Statement statement = CCJSqlParserUtil.parse(sql);
                for (SqlParserInterceptor s : interceptors) {
                    if (s.support()) {
                        try {
                            s.intercept(statement);
                        } catch (Exception e) {
                            logger.error(s.getClass().getName() + "处理" + sql + " error", e);
                        }
                    }
                }
                long end = System.currentTimeMillis();
                String newSql = statement.toString();
                long time = end - start;
                if (time > 50) {
                    logger.debug("解析sql用时{}ms, {} -> {}", (end - start), sql, newSql);
                }
                return newSql;
            } catch (JSQLParserException e) {
                logger.error(sql, e);
            }
        }
        return sql;
    }

}
